﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using ATPlatforms.RabbitSkin.Serializers;
using RabbitMQ.Client;
using RabbitMQ.Client.Exceptions;
using RabbitMQ.Client.MessagePatterns;

namespace ATPlatforms.RabbitSkin
{
    public abstract class BaseProducerConsumer : IDisposable
    {
        public string Server { get; set; }
        public string Exchange { get; set; }
        public string mQueue { get; set; }

        protected IModel Model { get; set; }
        protected IConnection Connection { get; set; }

        protected bool Running { get; set; }

        protected  string mExchangeType { get; set; }



        protected delegate void QueueWorkDelegate();

        protected Subscription mSubscription { get; set; }


        public BaseProducerConsumer(string server, string exchange, string exchangeType)
        {
            Server = server;
            Exchange = exchange;
            mExchangeType = exchangeType;
        }

        public void Dispose()
        {
            Running = false;
            if (mSubscription != null)
                mSubscription.Close();
            if (Connection!=null)
                Connection.Close();
            if (Model != null)
                Model.Abort();
        }

        public virtual bool StartBasic()
        {
            try
            {
                var connectionFactory = new ConnectionFactory();
                connectionFactory.HostName = Server;
                Connection = connectionFactory.CreateConnection();
                Model = Connection.CreateModel();
                if (!String.IsNullOrEmpty(Exchange))
                    Model.ExchangeDeclare(Exchange, mExchangeType, true);
                return true;
            }
            catch (BrokerUnreachableException e)
            {
                return false;
            }
        }
    }
}
